package com.mbbmap.security.action;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mbbmap.app.dao.SysLogDao;
import com.mbbmap.app.exception.LogonException;
import com.mbbmap.app.exception.UniqueKeyViolationException;
import com.mbbmap.app.home.SecGroupModule;
import com.mbbmap.app.home.SecUsersHome;
import com.mbbmap.app.home.SysLogHome;
import com.mbbmap.app.manager.ConfigManager;
import com.mbbmap.security.dao.SecGroupsDao;
import com.mbbmap.util.Constants;
import com.mbbmap.util.SecAccessHelper;
/*
 * Author: Luiz Santos
 * Date: 12/08/2013
 * Version: 1.0
 * 
 */
public final class UpdateGroupModules extends CommonDispatchAction {
	
	
	// Variables
	final String moduleCode = Constants.MDL_SEC_GROUP_MODULE;
	

		
    /*
     * On module load  initialize needed data
     */
    public ActionForward init(ActionMapping mapping,
    	    ActionForm form, HttpServletRequest request,
    	    HttpServletResponse response) throws Exception {

    	HttpSession session = request.getSession(false);
    	
        System.out.println("GroupModules.view :BEGIN");
        String test = "You got it";
        session.setAttribute("groupMsg", test);
        if(!isTokenValid(request)){
        	System.out.println("Token validation failed!");
			session.invalidate();
        	return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
        }else{
        	resetToken(request);
        	System.out.println("Token validation passed!");
        }
       
    	return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
    }
    
	
	  /**
	   * @author Luiz Santos
	   * Create a new Module and Group Entry
	   */
	  public ActionForward addModuleGroup(ActionMapping mapping,
	    ActionForm form, HttpServletRequest request,
	    HttpServletResponse response) throws Exception {

	    final String PROG_ID="UpdateUsersAction.addModuleGroup";
	    HttpSession session = request.getSession(false);
		System.out.println("UpdateUsersAction.java: addModuleGroup");
		String strESelectedGroupCode = (String) session.getAttribute(Constants.SELECTED_SEC_UGRP);
		// Login Information
		String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
		String strMerchant = "";
		String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);
		System.out.println(currLogonUserId);
		if ((strEMerchant != null) && (!strEMerchant.equals(""))){
			//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
		    strMerchant= strEMerchant;
		}else{
			strMerchant = "";
			return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}
		if(!isTokenValid(request)){
			System.out.println("Token validation failed!");
			session.invalidate();
			return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}else{
			resetToken(request);
			System.out.println("Token validation passed!");
		}
		
		if ( (currLogonUserId == null) || (currLogonUserId.equals("")) ){
		    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}
		
		boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
		if (!accessAllow) {
	        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
	    }

		String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
		if (roleCode == null || roleCode.trim().equals("")) {
		    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
		}
		
		ArrayList secGroupUserList = new ArrayList();
		String strSelectedGroupCode ="";
		String validIDFlag ="";
		String passwordResetFlag ="";
		
		// Get value from jsp
		String moduleCode = sanitize(request.getParameter("moduleCode"));
		String moduleName = sanitize(request.getParameter("moduleName"));
		
		
		System.out.println("UpdateGroupModules.java: addUsers_002 moduleCode " + moduleCode);
		//String strUserPWD = request.getParameter("UserPWD");
		System.out.println("UpdateGroupModules.java: addUsers_003 moduleName " + moduleName);

		String strErrLogonMsg = "";
		long secGroupDBId = -1;
		String secGroupModule = "";
		SysLogDao sysLogDao = new SysLogDao();

	    try{

				SecGroupsDao secGroup = new SecGroupsDao();
				secGroup.set(moduleCode, moduleName, "", "");
				
				// Activity log
				sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
				sysLogDao.setAcctID(strMerchant);
				sysLogDao.setActivityName(PROG_ID);
				sysLogDao.setUserID(currLogonUserId);
				sysLogDao.setRole(roleCode);

				secGroupModule = SecGroupModule.getInstance().createGroupModule(secGroup, strMerchant, currLogonUserId);
				if (secGroupModule  != "") {
				    sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
				}
				SysLogHome.getInstance().insertSysLog(sysLogDao);
		

				if ((strSelectedGroupCode != null) && (!strSelectedGroupCode.equals(""))){
					secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strMerchant,strSelectedGroupCode);
				}

				System.out.println("UpdateUsersAction.java: addModuleGroup_004 strSelectedGroupCode " + strSelectedGroupCode);
				System.out.println("UpdateUsersAction.java: addModuleGroup_005 secGroupUserList.size()" + secGroupUserList.size());
				//SQL COMMAND select a.logonid from bguser a inner join (property b inner join propertydefinition c on (b.idx = c.idx) and (c.uname = 'CSR_ROLE') and (b.value = 'SADMIN')) on a.id = b.id
				session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
				session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
				session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);


			//PersistServer.commitTransaction();


			//END (Market Direct Message) -- Added by ronnie( 20080918)

	    } catch (LogonException le) {
		    if (le.getErrorCode() == LogonException.USER_ID_PWD_SAME) {
		        strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_CHANGEPWD_PWD_SAME_USER_ID);
		    }
		}catch (UniqueKeyViolationException ukve) {
			System.out.println("Exception: " + ukve.toString());
			
			//strErrLogonMsg = Constants.LOGON_ERR_USER_ID_EXIST;
			strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_ADD_USER_LOGIN_ID_ALREADY_EXIST);
			sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
			sysLogDao.setUserField2(strErrLogonMsg);
			SysLogHome.getInstance().insertSysLog(sysLogDao);
			session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);
			//return mapping.findForward("error");
			return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
		}catch (Exception e) {
			System.out.println("Export error: " + e.toString());
			sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
			sysLogDao.setUserField2(e.getMessage());
			SysLogHome.getInstance().insertSysLog(sysLogDao);

			return mapping.findForward("error");
		}catch (Throwable e2) {
			System.out.println("Export error: " + e2.toString());
			sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
			sysLogDao.setUserField2(e2.getMessage());
			SysLogHome.getInstance().insertSysLog(sysLogDao);

			return mapping.findForward("error");
		}
		
	    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
	  }
	
	
	
	
	

}
